<template>
  <div class="search-panel">
    <div
      class="collapse-btn"
      :style="{ 'border-radius': collapsed ? '5px 5px 0 0' : '5px' }"
      @click="collapsed = !collapsed"
    >
      {{ collapsed ? "隐藏" : "搜索" }}
      <i :class="`el-icon-arrow-${collapsed ? 'up' : 'down'}`"></i>
    </div>
    <el-collapse-transition>
      <div v-show="collapsed" class="search-box">
        <div class="search-text">
          <el-input
            v-model="searchText"
            :placeholder="inputPlaceholder"
            @keyup.enter.native="handleSearch"
            size="normal"
          >
            <el-select v-model="searchType" slot="prepend" @change="searchTypeChange" size="normal" class="search-type">
              <el-option
                v-for="item in searchTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" size="normal" @click="search"></el-button>
          </el-input>
        </div>
        <div class="device-type" v-if="searchType == '0'">
          <el-tabs type="border-card" v-model="deviceType" @tab-click="handleTabClick">
            <el-tab-pane v-for="item in deviceTypeOptions" :label="item.label" :name="item.value" :key="item.label">
              <el-checkbox-group v-if="item.subtype.length > 0" v-model="item.selectedSubtype" class="device-subtype">
                <el-checkbox v-for="cItem in item.subtype" :label="cItem.typeId" :key="cItem.value">{{
                  cItem.label
                }}</el-checkbox>
              </el-checkbox-group>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="search-result">
          <el-table :data="tableData" style="width:100%" size="mini" highlight-current-row>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="position" label="定位" width="60">
              <template slot-scope="scope">
                <el-tag type="primary" @click="handleLocation(scope.row.position)">跳转</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            layout="prev, pager, next"
            @current-change="changePage"
            :current-page="page.pageNo"
            :page-size="page.pageSize"
            :total="page.total"
            style="text-align: right"
          ></el-pagination>
        </div>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script>
import mixins from '../mixins';
export default {
  name: 'SearchPanel',
  props: {
    getTool: {
      type: Function,
      required: true
    }
  },
  mixins: [mixins],
  data() {
    return {
      collapsed: true,
      searchType: localStorage.getItem('searchFirstType') || '1',
      inputPlaceholder: '',
      searchText: '',
      tableData: [],
      searchTypeOptions: [
        { label: '电网', value: '0', method: 'searchByServer' },
        { label: '地图', value: '1', method: 'searchByMap' }
      ],
      deviceType: '0',
      deviceTypeOptions: [
        {
          label: '电厂',
          value: '0',
          typeId: '300000',
          selectedSubtype: ['30000003', '30000099'],
          subtype: [
            {
              label: '火电厂',
              value: '0',
              typeId: '30000003'
            },
            {
              label: '水电厂',
              value: '1',
              typeId: '30000099'
            },
            {
              label: '风电厂',
              value: '2',
              typeId: '30000002'
            },
            {
              label: '太阳能电厂',
              value: '3',
              typeId: '30000010'
            }
          ]
        },
        {
          label: '电站',
          value: '1',
          typeId: '300000',
          selectedSubtype: ['30000001', '30000000'],
          subtype: [
            {
              label: '换流站',
              value: '0',
              typeId: '30000001'
            },
            {
              label: '变电站',
              value: '1',
              typeId: '30000000'
            },
            {
              label: '用户站',
              value: '2',
              typeId: '30000006'
            }
          ]
        },
        {
          label: '线路',
          value: '2',
          typeId: '100000',
          selectedSubtype: [],
          subtype: []
        },
        {
          label: '大馈线',
          value: '3',
          typeId: '100001',
          selectedSubtype: [],
          subtype: []
        },
        {
          label: '开关',
          value: '4',
          typeId: '111000,112000', // "305000,111000,307000,112000",
          selectedSubtype: ['11100000', '11200000'],
          subtype: [
            {
              label: '断路器',
              value: '0',
              typeId: '11100000'
            },
            {
              label: '负荷开关',
              value: '1',
              typeId: '11200000'
            }
          ]
        },
        {
          label: '配电设施',
          value: '5',
          typeId: '300000',
          selectedSubtype: ['32400000', '30000004'],
          subtype: [
            {
              label: '环网柜',
              value: '0',
              typeId: '32400000'
            },
            {
              label: '开闭站',
              value: '1',
              typeId: '30000004'
            },
            {
              label: '分支箱',
              value: '2',
              typeId: '20400000'
            },
            {
              label: '箱式变',
              value: '3',
              typeId: '32300000'
            },
            {
              label: '配电室',
              value: '4',
              typeId: '30000005'
            }
          ]
        },
        {
          label: '配变',
          value: '6',
          typeId: '110000',
          selectedSubtype: [],
          subtype: []
        }
      ],
      page: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      renderInstance: null
    };
  },
  methods: {
    searchTypeChange() {
      this.tableData = [];
      if (this.searchType === '0') {
        this.inputPlaceholder = this.deviceTypeOptions.find((item) => item.value === this.deviceType).label;
      } else if (this.searchType === '1') {
        this.inputPlaceholder = '';
      }
      localStorage.setItem('searchFirstType', this.searchType);
    },
    handleTabClick(tab) {
      this.inputPlaceholder = tab.label;
    },
    search() {
      this.page.pageNo = 1;
      this.handleSearch();
    },
    changePage(val) {
      this.page.pageNo = val;
      this.handleSearch();
    },
    handleSearch() {
      let searchText = this.searchText.trim();
      if (searchText === '') {
        return;
      }
      let searchTypeMap = {
        '0': 'searchByServer',
        '1': 'searchByMap'
      };
      let searchType = searchTypeMap[this.searchType];
      this[searchType]();
    },
    searchByMap() {
      let params = {
        query: this.searchText,
        region: '江苏',
        pageIndex: this.page.pageNo,
        pageSize: this.page.pageSize
      };
      this.getTool('SearchTool')
        .searchByMap(params)
        .then((res) => {
          console.log(res);
          let data = res.pois;
          data.forEach((item) => {
            item.name = item.text;
            item.address = item.place_name;
            item.position = item.center;
          });
          this.tableData = data;
          this.page.total = res.count;
        });
    },
    searchByServer() {
      let device = this.deviceTypeOptions.find((item) => item.value === this.deviceType);
      let params = {
        input: this.searchText,
        schema: this.option.schema,
        fxlx: this.option.fxlx,
        ghrw: this.option.ssghrw,
        ghfa: this.option.ssfa,
        ghxm: this.option.ssxm,
        ghnf: this.option.ghnf,
        verRule: this.option.verRule,
        sblx: device.typeId, //设备类型
        sbzlx: device.selectedSubtype.join(','), //设备子类型
        pageSize: this.page.pageSize,
        pageNum: this.page.pageNo
      };
      // get shape
      let bbox = this.getTool('BaseMapTool').getBounds();
      let polygon = turf.bboxPolygon(bbox);
      let geometry = polygon.geometry;
      geometry.coordinates = this.$MapUtils.CoordinateUtil.projectLngLatToWebMercator(geometry.coordinates);
      params.shape = this.$MapUtils.Geojson2WktUtil.parse(geometry);
      // query
      this.getTool('SearchTool')
        .searchByServer(params)
        .then((res) => {
          console.log(res);
          let data = res.datas;
          data.forEach((item) => {
            item.name = item.sbmc;
            item.address = '';
            item.position = '';
          });
          this.tableData = data;
        });
    },
    handleLocation(position) {
      if(this.renderInstance) {
        this.renderInstance.remove();
      }
      console.log(position);
      this.getTool('BaseMapTool').centerAt(position);
      let pointFeature = turf.point(position);
      pointFeature.properties.sourceType = 'Marker';
      pointFeature.properties.opacity = '1';
      pointFeature.properties.icon = 'label_red';
      pointFeature.properties.iconSize = 1;
      this.renderInstance = this.getTool('RenderTool').render([pointFeature]);
    }
  }
};
</script>

<style scoped>
.search-panel {
  position: fixed;
  left: 310px;
  top: 10px;
  width: 400px;
  z-index: 1;
}

.collapse-btn {
  width: 100px;
  height: 36px;
  line-height: 36px;
  background-color: rgba(45, 130, 248, 0.7);
  color: white;
  font-weight: 900;
  font-size: 16px;
  text-align: center;
  cursor: pointer;
}

.search-box {
  padding: 5px;
  background: #f2f2f2;
}

.search-type {
  width: 80px;
}

.device-type {
  width: 390px;
  margin-top: 10px;
}

.device-type >>> .el-tabs--border-card > .el-tabs__header .el-tabs__item {
  padding: 0 8px;
}

.device-type >>> .el-tabs--top.el-tabs--border-card > .el-tabs__header .el-tabs__item:first-child {
  margin-left: 10px;
}

.device-type >>> .el-tabs--top.el-tabs--border-card > .el-tabs__header .el-tabs__item:last-child {
  margin-right: 10px;
}

.device-type >>> .el-tabs__content {
  padding: 0 15px;
}

.device-subtype {
  padding: 15px 0;
}

.search-result {
  width: 390px;
  margin-top: 5px;
  background-color: #fff;
}

.search-result >>> .el-tag {
  cursor: pointer;
}
</style>
